package com.scc.servlet;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.scc.entites.DishEntity;
import com.scc.entites.dto.DishEntityDTO;
import com.scc.services.IDishSetupService;

@Controller
@RequestMapping(value = "/UpdateDish")
public class UpdateDish
{
   @Autowired
   IDishSetupService setupService;

   @RequestMapping(method = RequestMethod.GET)
   public String showForm(ModelMap model, @RequestParam("dishCode") String code)
   {
      DishEntity fromDB = setupService.getDish(code);
      DishEntityDTO dish = new DishEntityDTO();
      
      fillDTO(dish, fromDB);
      
      model.addAttribute("DISH", dish);
      return "update";
   }

   @RequestMapping(method = RequestMethod.POST)
   public String processForm(@ModelAttribute(value = "DISH")
   DishEntityDTO dish, BindingResult result)
   {
      setupService.updateDish(dish.getCode(), dish.getName(), dish.getDescription(), dish.getWeight());
      return "success";
   }
   
   private void fillDTO(DishEntityDTO dish, DishEntity fromDB)
   {
      dish.setCode(fromDB.getCode());
      dish.setName(fromDB.getName());
      dish.setWeight(fromDB.getWeight());
   }
}